/*
 * User: rant
 * Date: 08/01/2007
 *
 *
 */
package laMalinche.rete.nodes;

import laMalinche.rete.nodes.tailing.BasicTailingsConditionNode;
import laMalinche.rete.nodes.tailing.TailingManager;
import laMalinche.rete.nodes.tailing.PropertyTouchedListener;
import laMalinche.rete.rule.*;
import laMalinche.testingPlayGround.testModel.VOEntity;

import org.jetbrains.annotations.NotNull;

import java.util.*;
import static java.lang.Boolean.*;

/**
 This condition is tailing the action,change in one of the action relevant fields will make it true
 */
public class ActionTailingConditionNode extends BasicTailingsConditionNode implements ActionHolder, Condition, PropertyTouchedListener {
	private Action action;
	private boolean triger = true;

	public Action getAction() {
		return action;
	}

    public ActionTailingConditionNode() {
    }

    @Override
	public void initialize() {
		super.initialize();
		final ActObservable actObservable = getActObservable();
		final TailingManager tailingManager = actObservable.getTailingManager();
		tailingManager.addPropertyTouchedListener(this);
//		actObservable.addActListener(this);
	}

	@Override
	public void stopRuleExecution() {
//		setConditionMet(null);
		throw new StopEvaluatingException();
	}


	public void setAction(Action action) {
		this.action = action;
	}

	public void setTrigger(boolean triger) {
		this.triger = triger;
	}

	@Override
	public void update() {
		if (!FALSE.equals(isConditionMet()) && !isRelevant()) {
			setConditionMet(null);
			return;
		}
		setConditionMet(true);
		if (!isTriger() && FALSE.equals(isConditionMet())) {
			setConditionMet(null);
		}
	}

	public boolean isTriger() {
		return triger;
	}

	@NotNull
	@Override
	public Condition getCondition() {
		return this;
	}

	public boolean isDisjunction() {
		return true;
	}

	public boolean isComplied() {
		return true;
	}

	@Override
	public ActObservable getActObservable() {
		return (ActObservable) getAction();
	}

	@Override
	public boolean equals(Object condition) {
		return condition instanceof ActionTailingConditionNode &&
				((ActionTailingConditionNode) condition).getAction().equals(getAction());
	}

	public Progression getProgression() {
		return null;
	}

	public void propertyTouched(VOEntity entity) {
	}

	public void actCompleted(List<VOEntity> elements) {
			setConditionMet(null);
	}
}